#!/bin/bash

echo "Start radio $2 ($1)" | systemd-cat

URL=$1
if [ "$URL" == "" ]; then
  echo "call with $0 streamurl"
  exit 1
fi

# Start mpd if it isn't yet running
systemctl start mpd

STATIONNAME=$2
if [ "$STATIONNAME" != "" ]; then
  # URLs are often playlists or forwarders
  # extract the real URL of the stream using the musicdb web service
  URLSERVICE=http://musicdb.hifiberry.com/radio/url
  NEWURL=`curl -f -s -d stream="$URL" -d station="$STATIONNAME" -m 5 $URLSERVICE` 
fi

if [ "$NEWURL" != "" ]; then
 URL=$NEWURL
fi

if [[ $URL == *"opml.radiotime.com"* ]]; then
  echo "Retrieving real stream URL (this is a TuneIn URL)"
  URL=`curl $URL 2>/dev/null`
fi

# If there are multiple URLs, use only the first one
URL=`echo $URL | awk '{ print $1 }'`

mpc clear
mpc load $URL
if [ "$?" != 0 ]; then
  # This doesn't seem to be a playlist, but a direct link to the stream"
  mpc add $URL
fi
sleep 1
mpc play
